package filters;

import com.alibaba.fastjson.JSON;
import utilts.Response;
import utilts.ResponseCode;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class UserFilters implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        servletRequest.setCharacterEncoding("utf-8");
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String [] urll={"/api/login",".jpg","/api/reguster","/api/GetNotice","/api/HotBooks","/api/findproduc","/api/categcry","/api/books"};//放行数组
       String url= request.getRequestURL().toString();
       System.out.println(url);
       boolean flge=false;
       for (String u : urll){
           if(url.indexOf(u)>0)
           {
               flge=true;
               break;
           }

       }
       if(flge==false){
           HttpSession session=request.getSession();
           if(session.getAttribute("user")== null){
               System.out.println("111111111111111111111111");
               Response build = Response.build(ResponseCode.NOT_LOGIN);
               response.setContentType("application/json;charset=utf-8");
               response.getWriter().write(JSON.toJSON(build).toString());
           }
            else{
               filterChain.doFilter(request, response);
           }
       }
       else {//已经登录，把sessionid通过cookies写入到响应消息中,放行
           System.out.println("22222222");
//               Cookie cookie = new Cookie("JSESSIONID", session.getId());
//               response.addCookie(cookie);
           filterChain.doFilter(request, response);
       }
    }

    @Override
    public void destroy() {

    }
}
